package co.edu.unal.satacredito.queue;

import co.edu.unal.satacredito.database.connection.TransactionDatastoreFactory;
import co.edu.unal.satacredito.database.constants.TransactionConstants;
import co.edu.unal.satacredito.database.dao.TransactionMongoDao;
import co.edu.unal.satacredito.database.entity.Transaction;
import co.edu.unal.satacredito.ejbs.ValidationEJB;
import co.edu.unal.satacredito.queue.entity.TransactionPojo;
import com.google.code.morphia.Datastore;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.xml.ws.WebServiceRef;
import org.bson.types.ObjectId;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import webservice.EventLogWebService_Service;
import webservice.NonexistentEntityException_Exception;
import webservice.PreexistingEntityException_Exception;

@MessageDriven(mappedName = "jms/Queue")
public class QueueReader implements MessageListener {
    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/EventLogWebService.wsdl")
    private EventLogWebService_Service service;
    Datastore datastore;
    TransactionMongoDao tmd;
    public QueueReader() throws UnknownHostException {
       if(datastore == null){
           try {         
           this.datastore = TransactionDatastoreFactory.createDatastore();           
            } catch (Exception e) {
                //TO-DO
           }
       if(tmd == null){
           try{
           this.tmd = new TransactionMongoDao(this.datastore);
           }catch(Exception e){
               //TO-DO
           }
       }
       }
    }
    
    
    
  

    @Resource
    private MessageDrivenContext mdc;
    private static final Logger logger = null;

    @Override
    public void onMessage(Message msg) { 
         //System.out.println("ok");
        //MapMessage mmsg = null;
        ObjectMessage omsg = null;

        try {
            //mmsg = (MapMessage) msg;
            omsg = (ObjectMessage) msg;
            
            
            Transaction transactionOut = new Transaction();
            TransactionPojo transactionIn = (TransactionPojo) omsg.getObject();
            
            transactionOut.setFileId(new ObjectId(transactionIn.getFileId()));
            transactionOut.setFileNumber(transactionIn.getFileNumber());
            transactionOut.setName(transactionIn.getName());
            transactionOut.setNin(transactionIn.getNin());
            transactionOut.setNinType(transactionIn.getNinType());
            transactionOut.setCardCode(transactionIn.getCardCode());
            transactionOut.setCardNumber(transactionIn.getCardNumber());
            transactionOut.setCardType(transactionIn.getCardType());
            transactionOut.setCardExpirationDate(transactionIn.getCardExpirationDate());
            transactionOut.setBank(new ObjectId(transactionIn.getBank()));
            transactionOut.setFranchise(new ObjectId(transactionIn.getFranchise()));
            transactionOut.setPurchaseDate(new Date(transactionIn.getPurchaseDate()));
            transactionOut.setPurchaseAmount(transactionIn.getPurchaseAmount());
            transactionOut.setPurchaseDetail(transactionIn.getPurchaseDetail());          
            
            transactionOut.setValidationDate(null);
            transactionOut.setValidationResult(TransactionConstants.RESULT_NOT);
            transactionOut.setValidationIssue(TransactionConstants.ISSUE_NOT);
            transactionOut.setReadState(TransactionConstants.READ_SYNTAXIS);
           
            
            System.out.println("QueueReader: "+transactionIn);
            
            
            
            
            
            
            
            ValidationEJB vejb = new ValidationEJB();
            
            try {
            ObjectId TrazaId = tmd.create(transactionOut);
            String token = startProcess(vejb.getMachineName(), TrazaId.toString(), 1);
            finalizeProcess(token);
            System.out.println("Transaction id: "+TrazaId);
            System.out.println("Transaction id: "+TrazaId.toString());
           
            } catch (Exception e) {
                e.printStackTrace();
            }
           
             System.out.println("QueueReader: Received from Queue");
             
        } catch (Exception e) {
            e.printStackTrace();
            mdc.setRollbackOnly();
        } catch (Throwable th) {
            th.printStackTrace();
            
        }
    }

    public void ejbRemove() throws EJBException {
        logger.fine("ejbRemove()");
    }

    private String startProcess(java.lang.String machineName, java.lang.String fileCheck, int typeOfWork) throws NonexistentEntityException_Exception, PreexistingEntityException_Exception {
        webservice.EventLogWebService port = service.getEventLogWebServicePort();
        return port.startProcess(machineName, fileCheck, typeOfWork);
    }

    private String finalizeProcess(java.lang.String token) {
        webservice.EventLogWebService port = service.getEventLogWebServicePort();
        return port.finalizeProcess(token);
    }

  
}